package com.hckj.jianzhijia;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.SaveCallback;
import com.hckj.jianzhijia.interfaces.UserInfoChangeInterface;
import com.hckj.jianzhijia.listeners.OnBackClickListener;
import com.hckj.jianzhijia.model.CompanyUser;
import com.hckj.jianzhijia.popupwindows.ChangeLogoPopWin;
import com.hckj.jianzhijia.utils.BitmapUtils;
import com.hckj.jianzhijia.utils.Data;
import com.hckj.jianzhijia.utils.ExceptionUtils;
import com.hckj.jianzhijia.utils.ToastUtils;
import com.hckj.jianzhijia.views.RoundImageView;
import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.squareup.picasso.Picasso;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class CompanyActivity extends BaseActivity implements UserInfoChangeInterface, ChangeLogoPopWin.PopWinInterface {

    @InjectView(R.id.rl_toolbar)
    RelativeLayout rlToolbar;
    @InjectView(R.id.imgv_company_logo)
    RoundImageView imgvCompanyLogo;
    @InjectView(R.id.tv_company_name)
    TextView tvCompanyName;
    @InjectView(R.id.rl_change_company_name)
    RelativeLayout rlChangeCompanyName;
    @InjectView(R.id.tv_company_address)
    TextView tvCompanyAddress;
    @InjectView(R.id.rl_change_company_address)
    RelativeLayout rlChangeCompanyAddress;
    @InjectView(R.id.tv_company_desc)
    TextView tvCompanyDesc;
    @InjectView(R.id.rl_change_company_desc)
    RelativeLayout rlChangeCompanyDesc;
    @InjectView(R.id.imgv_go_back)
    ImageView imgvGoBack;
    @InjectView(R.id.rl_change_logo)
    RelativeLayout rlChangeLogo;
    @InjectView(R.id.tv_company_email)
    TextView tvCompanyEmail;
    @InjectView(R.id.rl_change_company_email)
    RelativeLayout rlChangeCompanyEmail;
    @InjectView(R.id.rl_parent)
    RelativeLayout rlParent;

    private ChangeLogoPopWin changeLogoPopWin;
    private ProgressDialog loadingDialog;
    private static final String picTempFile = Data.sdpath + "pic";
    static final String tele = "0631-5678650";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_company);
        ButterKnife.inject(this);
        ((JianzhijiaApplacation) getApplication()).addUserInfoChange(this);
        changeLogoPopWin = new ChangeLogoPopWin(this, this, rlParent, rlChangeLogo);
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setCancelable(false);
        loadingDialog.setMessage("正在上传");
        initData();
        initEvent();

    }

    private void initData() {

        CompanyUser companyUser = jianzhijiaApplacation.getCompanyUser();
        if (jianzhijiaApplacation.getCompanyUser().getLogo() != null) {
            Picasso.with(this).load(companyUser.getLogo().getUrl()).into(imgvCompanyLogo);
        }
        tvCompanyName.setText(companyUser.getName());
        tvCompanyDesc.setText(companyUser.getDescription());
        tvCompanyEmail.setText(companyUser.getEmail());
        tvCompanyAddress.setText(companyUser.getProvinceName() +
                                             companyUser.getCityName() +
                                             companyUser.getRegionName() +
                                             companyUser.getCompanyAddress());
    }

    private void initEvent() {

        imgvGoBack.setOnClickListener(new OnBackClickListener(this));
        rlChangeCompanyName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    String content = "为了您的账号信息安全，ScholarLink暂时不提供修改姓名的功能，如需修改请联系客服人员，联系电话：" + tele;
                    showMaterialDialog(content, "提示", new DialogAction() {
                        @Override
                        public void positiveAction() {
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tele));
                            startActivity(intent);
                        }

                        @Override
                        public void negativeAction() {

                        }
                    });
                }
                // TODO: 2015-12-07 下边是修改姓名的界面
                //startActivity(new Intent(getApplicationContext(), ChangeNameActivity.class));
        });

        rlChangeCompanyAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (jianzhijiaApplacation.getCompanyUser().isIdentified()) {
                    String content = "您已申请认证，我们将对您的基本信息进行保护，如要申请修改工作地址，请联系客服人员，联系电话：" + tele;
                    showMaterialDialog(content, "提示", new DialogAction() {
                        @Override
                        public void positiveAction() {
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tele));
                            startActivity(intent);
                        }

                        @Override
                        public void negativeAction() {

                        }
                    });
                } else {
                    startActivity(new Intent(getApplicationContext(), ChangeAddressActivity.class));
                }
            }
        });

        rlChangeCompanyDesc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), ChangeDescActivity.class));
            }
        });
        rlChangeCompanyEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (jianzhijiaApplacation.getCompanyUser().isIdentified()) {
                    String content = "您已申请认证，我们将对您的基本信息进行保护，如要申请修改工作邮箱，请联系客服人员，联系电话：" + tele;
                    showMaterialDialog(content, "提示", new DialogAction() {
                        @Override
                        public void positiveAction() {
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + tele));
                            startActivity(intent);
                        }

                        @Override
                        public void negativeAction() {

                        }
                    });
                } else {
                    startActivity(new Intent(getApplicationContext(), ChangeEmailActivity.class));
                }
            }
        });

    }


    @Override
    public void modifyFromAlbum(int position) {
        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        intent.putExtra("return-data", true);
        startActivityForResult(intent, MainActivity.CHOOSE_PHOTO);

    }

    @Override
    public void modifyFromPhoto(int position) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//调用android自带的照相机
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(picTempFile)));
        startActivityForResult(intent, MainActivity.GET_PHOTO);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        Bitmap bitmap = null;
        if (requestCode == MainActivity.GET_PHOTO && resultCode == Activity.RESULT_OK) {
            bitmap = BitmapUtils.compressImage(BitmapUtils.compressImageFromFile(picTempFile),200);
        } else if (data != null && requestCode == MainActivity.CHOOSE_PHOTO && resultCode == Activity.RESULT_OK) {
            Uri originalUri = data.getData();
            String path;
            Cursor cursor = managedQuery(originalUri, new String[]{MediaStore.Images.Media.DATA}, null, null, null);
            if(cursor != null){
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                path = cursor.getString(column_index);
            }else{
                path = originalUri.getPath();
            }
            bitmap = BitmapUtils.compressImage(BitmapUtils.compressImageFromFile(path),100);
        }
        if (bitmap == null) {
            return;
        }
        PicUpLoadNetTask picUpLoadNetTask = new PicUpLoadNetTask(bitmap);
        picUpLoadNetTask.execute();

    }

    @Override
    public void updateCompanyInfo() {
        tvCompanyName.setText(jianzhijiaApplacation.getCompanyUser().getName());
        tvCompanyDesc.setText(jianzhijiaApplacation.getCompanyUser().getDescription());
        tvCompanyEmail.setText(jianzhijiaApplacation.getCompanyUser().getEmail());
        tvCompanyAddress.setText(jianzhijiaApplacation.getCompanyUser().getProvinceName() +
                                             jianzhijiaApplacation.getCompanyUser().getCityName() +
                                             jianzhijiaApplacation.getCompanyUser().getRegionName() +
                                             jianzhijiaApplacation.getCompanyUser().getCompanyAddress());
    }

    @Override
    public void updateCompanyLogo() {
        Picasso.with(CompanyActivity.this).load(jianzhijiaApplacation.getCompanyUser().getLogo().getUrl()).into(imgvCompanyLogo);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ((JianzhijiaApplacation) getApplication()).removeUserInfoChangeInterface(this);

    }

    private void showMaterialDialog(String content, String title, final DialogAction dialogAction) {

        Dialog.Builder builder = null;
        builder = new SimpleDialog.Builder(R.style.SimpleDialogLight) {
            @Override
            public void onPositiveActionClicked(DialogFragment fragment) {
                fragment.dismiss();
                dialogAction.positiveAction();
                super.onPositiveActionClicked(fragment);
            }

            @Override
            public void onNegativeActionClicked(DialogFragment fragment) {
                fragment.dismiss();
                dialogAction.negativeAction();
                super.onNegativeActionClicked(fragment);
            }
        };

        ((SimpleDialog.Builder) builder).message(content)
                    .positiveAction("确认")
                    .negativeAction("取消").title(title);
        DialogFragment fragment = DialogFragment.newInstance(builder);
        fragment.setCancelable(false);
        fragment.show(getSupportFragmentManager(), null);
    }

    private interface DialogAction {
        void positiveAction();
        void negativeAction();
    }

    class PicUpLoadNetTask extends AsyncTask<Void, Void, String> {


        Bitmap bitmap = null;

        public PicUpLoadNetTask(Bitmap bitmap) {
            this.bitmap = bitmap;
        }

        @Override
        protected void onPostExecute(String s) {
            ToastUtils.showToast(getApplicationContext(), s);
            loadingDialog.dismiss();
            jianzhijiaApplacation.updateCompanyLogo();
            if (s.equals("图片上传成功")) {

            }
            super.onPostExecute(s);
        }

        @Override
        protected void onPreExecute() {
            loadingDialog.show();
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            AVFile avFile = new AVFile("logo" + jianzhijiaApplacation.getCompanyUser().getPhone(), baos.toByteArray());
            try {
                avFile.save();
                jianzhijiaApplacation.getCompanyUser().setLogo(avFile);
                jianzhijiaApplacation.getCompanyUser().saveUserInfo().save();
                return "图片上传成功";
            } catch (AVException e) {
                e.printStackTrace();
                return "图片上传失败" + ExceptionUtils.getExceptionInfo(e);
            }
        }
    }


}
